package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 地区资源控制器
 */
@RequestMapping("/region")
@Controller
public class RegionController {
    @Autowired
    private IRegionService regionService;

    @RequestMapping("/list")
    public String list() {
        return "region/list";
    }

    /** nodes: [
     * {
     *     text: 'Grandchild 1',
     *             tags: ['0']
     * },
     * {
     *     text: 'Grandchild 2',
     *             tags: ['0']
     * }
     *                         ]
     */
    @RequestMapping("/selectByParentId")
    @ResponseBody
    public List selectByParentId(Long parentId,String type) {
        /**
         * 区分treeView
         */
        String KEY_TYPE = "tree";
        //先拿到跟地区数据，弄成map类型的集合
        List<Region> regions = regionService.selectByParentId(parentId);
        if (KEY_TYPE.equals(type)) {
            ArrayList<Object> list = new ArrayList<>();
            for (Region region : regions) {
                Map map = region.toTreeMap();
                list.add(map);
            }
            return list;
        } else {
            return regions;
        }
    }
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JSONResult saveOrUpdate(Region region) {
        JSONResult jsonResult = new JSONResult();
        regionService.saveOrUpdate(region);
        return jsonResult;
    }
    @RequestMapping("/updateState")
    @ResponseBody
    public JSONResult updateState(Long id,Long  state) {
        JSONResult jsonResult = new JSONResult();
        regionService.updateState(id,state);
        return jsonResult;
    }
}
